<template>
<div class="articleList">
  <van-pull-refresh
  v-model="isRefreshLoading"
  :success-text="successText"
  :success-duration="1500"
  @refresh="onRefresh"
  >
    <van-list
    v-model="loading"
    :finished="finished" finished-text="没有更多了"
    :error.sync="error"
    error-text="请求失败，点击重新加载"
    @load="onLoad"
    >
      <!-- <van-cell v-for="(item,index) in list" :key="index" :title="item.title" /> -->
      <article-item :article="item" v-for="item in list" :key="item.art_id"></article-item>
    </van-list>
  </van-pull-refresh>
</div>
</template>

<script>
import { getArticles } from '@/api/article.js'
import ArticleItem from '@/components/article-item'
export default {
  name: 'articlaeList',
  props: {
    // key是要接收的数据，value是一个对象
    channel: {
      type: Object, // 接收数据类型
      required: true // 是否必传
    }
  },
  data () {
    return {
      list: [], // van-list组件数据
      loading: false, // 显示loding
      finished: false,
      timestamp: null, // 获取数据时间戳
      // 显示更多
      error: false,
      isRefreshLoading: false,
      successText: ''
    }
  },

  created () {
    // getArticles ()
  },
  components: {
    ArticleItem
  },
  methods: {
    async onLoad () {
      // load加载不够一整屏，会一只执行
      // 1、发送请求
      try {
        const { data: res } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })
        // 制造错误
        // if (Math.random() > 0.5) {
        //   return console.og('12')
        // }
        // console.log(res.data)
        // 2、得到数据，追加给list
        this.list.push(...res.data.results)
        if (res.data.result.length) {
          this.timestamp = res.data.pre_timestamp
        } else {
          // this.loading = true
          this.finished = true
        }
      } catch (err) {
        // this.$toast.fail('获取文章列表失败')
        this.loading = false
        this.error = true
      }
      // 3、加载状态结束，本次加载数据结束
      this.loading = false
      // const data = res.data
      // 4、数据全部加载完成,关闭加载更多数据
    },
    // 下拉刷新
    async onRefresh () {
      try {
        const { data: res } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(),
          with_top: 1
        })
        // 制造错误
        // if (Math.random() > 0.5) {
        //   return console.og('12')
        // }
        // console.log(res.data)
        // 2、得到数据，追加给list
        this.list = []
        this.list.unshift(...res.data.results)
        this.isRefreshLoading = false
        this.successText = `刷新成功，加载了${res.data.results.length}条`
      } catch (err) {
        // this.$toast.fail('获取文章列表失败')
        this.successText = '加载失败'
        this.isRefreshLoading = false
      }
    }
  }
}

</script>

<style scoped lang='less'>
  .articleList {
    height: 80vh;
    overflow-y: scroll;
  }

</style>
